package com.example.myapplication;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.appcompat.app.AppCompatActivity;

public class AdVideoActivity extends AppCompatActivity {

    private VideoView videoView;
    private TextView adTimer;
    private Button closeAdButton;
    private Handler handler;
    private Runnable updateTimerRunnable;
    private int currentPosition = 0;
    private int totalDuration = 0;
    private int skipAfterSeconds;
    private static final int DEFAULT_SKIP_AFTER = 5; // 默认5秒后可跳过

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ad_video);

        videoView = findViewById(R.id.videoView);
        adTimer = findViewById(R.id.adTimer);
        closeAdButton = findViewById(R.id.closeAdButton);
        handler = new Handler(Looper.getMainLooper());

        // 从Intent获取可跳过时间，默认为5秒
        skipAfterSeconds = getIntent().getIntExtra("skip_after_seconds", DEFAULT_SKIP_AFTER);

        playAdVideo();
        startTimer();
    }

    private void playAdVideo() {
        // 使用R.raw资源ID引用本地视频
        Uri videoUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.b);
        videoView.setVideoURI(videoUri);
        videoView.start();

        // 获取视频总时长
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                totalDuration = mp.getDuration() / 1000; // 转换为秒
                updateTimer();
            }
        });

        // 设置视频播放完成监听器
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                // 停止计时器
                handler.removeCallbacks(updateTimerRunnable);
                // 视频播放完毕后自动跳转
                startLevelSelectActivity();
            }
        });

        // 设置错误监听器
        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                // 停止计时器
                handler.removeCallbacks(updateTimerRunnable);
                Toast.makeText(AdVideoActivity.this, "广告播放失败，将跳转到主界面", Toast.LENGTH_SHORT).show();
                startLevelSelectActivity();
                return true;
            }
        });
    }

    private void startTimer() {
        updateTimerRunnable = new Runnable() {
            @Override
            public void run() {
                if (videoView.isPlaying()) {
                    currentPosition = videoView.getCurrentPosition() / 1000; // 转换为秒
                    updateTimer();

                    // 更新关闭按钮状态
                    updateCloseButton();
                }
                handler.postDelayed(this, 1000); // 每秒更新一次
            }
        };
        handler.postDelayed(updateTimerRunnable, 0);
    }

    private void updateTimer() {
        // 计算剩余时间
        int remainingTime = totalDuration - currentPosition;
        String timeString = String.format("%02d:%02d",
                remainingTime / 60,
                remainingTime % 60);
        adTimer.setText(timeString);
    }

    private void updateCloseButton() {
        int remainingSkipTime = skipAfterSeconds - currentPosition;

        if (remainingSkipTime > 0) {
            // 还不能跳过，显示剩余时间
            closeAdButton.setText("剩余" + remainingSkipTime + "秒可关闭");
            closeAdButton.setEnabled(false);
        } else {
            // 可以跳过，启用按钮
            closeAdButton.setText("关闭广告");
            closeAdButton.setEnabled(true);
            closeAdButton.setTextColor(getResources().getColor(android.R.color.white));
            closeAdButton.setBackgroundTintList(getResources().getColorStateList(android.R.color.holo_red_dark));
        }
    }

    public void closeAd(View view) {
        // 用户点击关闭广告
        handler.removeCallbacks(updateTimerRunnable);
        startLevelSelectActivity();
    }

    private void startLevelSelectActivity() {
        // 广告播放结束后跳转到关卡选择页面
        Intent intent = new Intent(AdVideoActivity.this, LevelSelectActivity.class);
        startActivity(intent);
        finish(); // 关闭广告页面，防止返回
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(updateTimerRunnable);
    }
}